package com.ruoyi.service.impl;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.domain.Image;
import com.ruoyi.mapper.ImageMapper;
import com.ruoyi.service.ITransService;
import com.ruoyi.util.CosClientUtil;
import com.ruoyi.util.DateUtil;
import com.ruoyi.web.controller.wechat.request.TransImageRequest;
import com.ruoyi.web.controller.wechat.response.TransImageResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * TODO
 *
 * @author chenchuan2
 * @date 2023-01-13 17:46:06
 */
@Service
@Slf4j
public class TransServiceImpl implements ITransService {

    @Autowired
    private ImageMapper imageMapper;

    @Autowired
    private CosClientUtil cosClientUtil;

    @Override
    public void transImage(String openId, TransImageRequest request, TransImageResponse image) throws IOException {

        //把base64转url
        String userImg = StringUtils.isNotEmpty(request.getImageUrl()) ? request.getImageUrl()
                : cosClientUtil.uploadImgToCos(request.getImageBase64(), request.getFileName());
        String userImgHash = request.getImageBase64().hashCode() + "";

        //把腾讯云转自己的cos
        String transImg = cosClientUtil.downloadUsingStream(image.getTransUrl());

        Image img = new Image();
        img.setOpenId(openId);
        img.setUserImg(userImg);
        img.setTransImg(transImg);
        img.setUserImgHash(userImgHash);
        img.setRequestId(image.getTransId());
        img.setCreateDay(DateUtil.getNowDefault());

        imageMapper.insertSelective(img);
        image.setTransUrl(transImg);
    }

    @Override
    public Image queryUserImage(String openId, String imageHash) {
        return imageMapper.queryUserImage(openId, imageHash);
    }

    @Override
    public void updateImageTime(Image image) {
        imageMapper.updateImageTime(image.getId());
    }

    @Override
    public Image queryByTransId(String transId) {
        return imageMapper.queryByTransId(transId);
    }

    @Override
    public Image queryNewest(String openId) {
        return imageMapper.queryNewest(openId);
    }

}
